import {
	mapState
} from 'vuex'
import {
	setColumnsSearchInfo,
	getColumnsSearchInfo
} from '@/utils/base'
import QS from 'qs';
// 注入全局minix
export default {
	computed: {
		...mapState({
			isAdmin: state => state.user.isAdmin,
			isMangAdmin: state => state.user.isMangAdmin,
			globalOrgId: state => state.globalOrg && state.globalOrg.orgId,
			eventlist: state => state.websockStore.eventlist,
			userinfo: (state) => state.user.userinfo,
			isDoctor: state => state.user.isDoctor,
		}),
		/* eventlist() {
			return this.$store.getters.onEvent('answer');
		}, */
		basefileUrl() {
			return process.env.VUE_APP_FILE_API
		},
		wsUrl() {
			return process.env.VUE_APP_WS_API
		},

	}
}
export const rowSelection = {
	data() {
		return {
			selectedRowKeys: [],
		}
	},
	computed: {

	},
	watch: {
		globalOrgId(newValue, oldValue) {
			this.$nextTick(() => {
				this.$refs.protable && this.$refs.protable.handlerRefresh();
			});
		}
	},
	created() {

	},
	methods: {
		/* 选中checkbox */
		onSelectChange(selectedRowKeys) {
			this.selectedRowKeys = selectedRowKeys;
			const selectedRowChange = this.$listeners['selectedRowChange'];
			if (selectedRowChange && typeof selectedRowChange === 'function') {
				selectedRowChange(selectedRowKeys);
			}
		},
		//获取选择行数据
		getSelectedRow(list, rowKey) {
			let selectedRow = [];
			selectedRow = list.filter(item => {
				if (this.selectedRowKeys.indexOf(item[rowKey]) > -1) {
					return item;
				}
			})
			return selectedRow
		}

	}
};




var answerCount = 0;
let seq = 0; //序号
var studentIndex = -1;
var studentName = "";
var studentClass = "";
//学生的姓名班级需要全部配置时 所有学生信息的json集合
var jsonArr = [];
//var uuidSet = [];//答题器ID数组
var answerCountArray = new Array();
var fileByteArray = [];
var answerFileByteArray = [];
//升级文件
var file = "";
var answerFile = "";
var md5String = "";
var answerMd5String = "";
var length = 0;
var answerLength = 0;



var intToByteArray = function(number, length) {
	let bytes = [];
	let i = length;
	do {
		bytes[--i] = number & 255;
		number = number >> 8;
	} while (i);
	return bytes;
};


var stringToBytes = function(str) {
	var bytes = [];
	for (var i = 0; i < str.length; i++) {
		var charCode = str.charCodeAt(i);
		bytes.push(charCode);
	}
	return bytes;
}


function bitsToBytes(bits) {
	var bytes = [];
	for (var i = 0; i < bits.length; i += 8) {
		var byteBits = bits.slice(i, i + 8);
		var byte = 0;
		for (var j = 0; j < byteBits.length; j++) {
			byte = (byte << 1) | byteBits[j];
		}
		bytes.push(byte);
	}
	return bytes;
}

var isChineseCharacter = function(str) {
	var reg = /^[\u4e00-\u9fa5]+$/;
	return reg.test(str);
}


var getCharData = function(str) {
	var byteList = Array()
	for (let index = 0; index < str.length; index++) {
		const char = str[index];
		var data = getCharBytes(char);
		data.forEach(it => {
			byteList.push(it);
		});
	}
	return byteList;
}

import md5 from 'md5';
//列表的增删改查
export const recordOperation = {
	data() {
		return {
			checkpassword:''
		}
	},
	methods: {
		/* 刷新列表当前页 */
		handlerRefresh(type) {
			this.$refs.protable.handlerRefresh(type);
		},
		/* 新增 */
		addRecord() {
			this.$refs.addOrEditModal.add();
		},
		/* 编辑 */
		editRecord(record) {
			this.$refs.addOrEditModal.edit(record);
		},
		/* 查看 */
		viewRecord(record, api) {
			this.$refs.detailModal.show(record, api);
		},
		/* 导入 */
		importRecord() {
			this.$refs.uploadModal.show();
		},
		/*导出*/
		/* exportRecord(delIds) {
			this.$postAction(this.api.export, delIds).then(res => {
				if (res && res.code == 1) {
					this.$message.success('导出成功！');
					this.handlerRefresh();
				}
			});
		}, */
		/* 确认是否删除 */
		showDeleteConfirm(type, delId, name) {
			let _this = this;
			let title, ids;
			if (type == 0) {
				title = '你确定删除选中的' + this.selectedRowKeys.length + '条数据吗？';
				ids = this.selectedRowKeys.map(item => item);
			} else {
				title = ( <div> 你确定要删除 <span style = "color:red;" > {
					name ? '(' + name + ')' : ''
				} </span>吗 ?</div> );
				ids = [delId];
			}
			
			if(this.userinfo.delVerify){
				this.checkpassword='';
				this.$confirm({
					title:title,
					content: (h) => (
						<a-form autocomplete="off">
							<a-form-item label="删除后信息将不能恢复" help="删除需要校验密码，如不需要请在基础数据-其他设置中取消">
								<a-input type="password" placeholder="请输入校验密码" v-model={this.checkpassword} />
							</a-form-item>
						</a-form>
					),
					okText: '确定',
					cancelText: '取消',
					class: 'confirmbox',
					okType: 'danger',
					onOk: async () => {
						await this.delVerify(this.checkpassword, ids);
					},
					onCancel() {},
				});
			}else{
			this.$confirm({
				title: title,
				content:'删除后信息将不能恢复' ,
				okText: '确定',
				cancelText: '取消',
				class: 'confirmbox',
				okType: 'danger',
				onOk() {
					_this.removeRecord(ids);
				},
				onCancel() {}
			});
			}
		},
		/* 校验密码 */
		delVerify(checkpassword, delIds) {
			return new Promise((resolve, reject) => {
				if(!checkpassword){
					this.$message.error('请输入校验密码');
					reject();
				}
				let md5Pass = md5(checkpassword.trim());
				this.$postAction(this.$api.delVerify, {
					md5Pass,
					password: checkpassword,
					userId: this.userinfo.userId,
				}).then((res) => {
					if (res && res.code == 1 && res.data == 1) {
						this.removeRecord(delIds);
						resolve();
					} else {
						this.$message.error('密码错误，请重新输入密码');
						reject();
					}
				});
			});
		},
		/*删除*/
		removeRecord(delIds) {
			this.$postAction(this.api.delete, delIds).then(res => {
				if (res && res.code == 1) {
					this.$message.success('删除成功！');
					this.handlerRefresh();
				}
			});
		},
		setColumnsSearchInfo,
		getColumnsSearchInfo,
		//获取筛选条件并更新表格列
		getFilterDefaultValue() {
			let filterparam = this.$refs.protable.$refs.filterbars.getFilterDefaultValue();
			console.log('操作的条件' + JSON.stringify(filterparam));
			let columns = JSON.parse(JSON.stringify(this.columns));
			columns.forEach(item => {
				for (var key in filterparam) {
					if (item.searchInfo) {
						//这里分两种情况有时候添加了筛选条件没有设置value值，就用dataIndex判断，并赋值默认值(原始defaultValue!=新的筛选默认值时)
						if ((item.searchInfo.value && item.searchInfo.value == key) || (!item.searchInfo
								.value && item.dataIndex == key)) {
							if (item.searchInfo.defaultValue != filterparam[key]) {
								item.searchInfo.defaultValue = filterparam[key];
							}
						}
					}
				}
			});
			this.columns = [...columns];
			console.log('获取筛选条件并更新表格列' + JSON.stringify(this.columns));
		},


	}
};
export const tableResize = {
	data() {
		return {
			scrolly: 500,
			viewlistTop: 0,
			filterbarHeight: 72

		}
	},
	mounted() {
		if (this.$refs.filterbar) {
			this.filterbarHeight = this.$refs.filterbar.offsetHeight;
		}
	},
	methods: {
		onResize(resize) {
			let marginTop = 10;
			let tableHeader = 44;
			let tableFooter = 80;
			this.scrolly = resize.height - tableHeader - tableFooter;
			if (this.$refs.filterbar) {
				this.filterbarHeight = this.$refs.filterbar.offsetHeight;
			}
		}
	}
};
/* 弹出框的公共设置 */
export const ModalMixins = {
	data() {
		return {
			labelCol: {
				xs: {
					span: 24
				},
				sm: {
					span: 5
				}
			},
			wrapperCol: {
				xs: {
					span: 24
				},
				sm: {
					span: 16
				}
			},
			visible: false,
			confirmLoading: false,
			mdl: {},
			form: this.$form.createForm(this),
			title: '新增',
			isAdd: true
		}
	},
	props: {
		//接口地址
		api: {
			type: Object,
			default: () => {}
		},
		//标题
		modalTitle: {
			type: String,
			default: ''
		},
		//编辑的唯一标识
		editKey: {
			type: String,
			default: ''
		}
	},
	methods: {
		/** 
		 * @description  输入转换成大写
		 * @param {Object} value
		 */
		normalizeUp(value) {
			return value ? value.toUpperCase() : '';
		},
		/**
		 * @description  清除输入框中的空格
		 * @param {Object} e change事件的参数
		 */
		removeSpaces(e) {
			return e.target.value.trim();
			// return e.target.value.replace("\\u200B","")
		},
		//下拉框筛选
		filterOption(input, option) {
			return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
		},
		add(record) {
			this.isAdd = true;
			this.initInfo(record);
		},
		edit(record) {
			this.isAdd = false;
			this.initInfo(record);
		},
		initInfo(record = {}) {
			this.mdl = Object.assign({}, record);
			this.title = (this.isAdd ? '新增' : '编辑') + this.modalTitle;
			this.visible = true;
			//获取一些初始下拉数据
			this.getDefaultList && this.getDefaultList();
			this.$nextTick(() => {
				this.form.resetFields();
				this.setFieldsValue()
			});
		},
		/**
		 * 数据的回填
		 */
		setFieldsValue() {
			if (!this.isAdd) {
				/* 如果有编辑回填方法，嗲用编辑回填，否则调用默认方法 */
				if (this.setEditFieldsValue && typeof this.setEditFieldsValue === 'function') {
					this.setEditFieldsValue()
				} else {
					/* 先获取所有的item 然后赋值 */
					let list = Object.keys(this.form.getFieldsValue());
					// console.log("list", list);
					let fieldNames = list.filter(item => item != 'orgId')
					// console.log('this.$pick(this.mdl, ...fieldNames)', this.$pick(this.mdl, ...fieldNames))
					this.form.setFieldsValue(this.$pick(this.mdl, ...fieldNames));
					if (this.isAdmin && list.includes('orgId')) {
						this.form.setFieldsValue({
							orgId: this.mdl.orgId
						});
					}
				}

			} else if (this.setAddFieldsValue) {
				/* 如果有新增默认数据 回填新增默认数据 */
				typeof this.setAddFieldsValue === 'function' && this.setAddFieldsValue()
			}
		},

		/**
		 * 点击确认按钮
		 */
		handleOk() {
			// 触发表单验证
			this.form.validateFields((err, values) => {
				console.log("Coder", values);
				// 验证表单没错误
				if (!err) {
					/* 处理地址 */
					let id = this.mdl[this.editKey];
					let parameter = Object.assign({}, values, id ? {
						[this.editKey]: id
					} : '');
					this.saveInfo(this.isAdd ? this.api.add : this.api.edit, parameter);
				}
			});
		},
		/**
		 * 关闭弹出
		 */
		handleCancel() {
			this.confirmLoading = false;
			this.$emit('close');
			this.visible = false;
		},
		//保存数据
		saveInfo(url, parames) {
			this.confirmLoading = true;
			this.$postAction(url, parames)
				.then(res => {
					console.log(res);
					if (res && res.code == 1) {
						this.$message.success('保存成功');
						this.$emit('ok');
						this.form.resetFields();
						this.visible = false;
					}
				})
				.finally(() => {
					this.confirmLoading = false;
				});
		},
	}
};